package com.unit.dbutils.handler;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Calendar;

import org.apache.commons.dbutils.ColumnHandler;

public class TimeGeneralHandler implements ColumnHandler {
	
	private Class<?> clazz;
	
	@Override
	public boolean match(Class<?> propType) {
		
		clazz = propType;
		
		if(propType.equals(LocalDateTime.class)) {
			return true;
		}else if(propType.equals(LocalDate.class)) {
			return true;
		}else if(propType.equals(Calendar.class)) {
			return true;
		}		
		return false;
	}

	@Override
	public Object apply(ResultSet rs, int columnIndex) throws SQLException {
		if (rs.getTimestamp(columnIndex) != null) {
			if(clazz.equals(LocalDateTime.class)) {
				return rs.getTimestamp(columnIndex).toLocalDateTime();
			}else if(clazz.equals(LocalDate.class)) {
				return rs.getTimestamp(columnIndex).toLocalDateTime().toLocalDate();
			}else if(clazz.equals(Calendar.class)) {
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(rs.getTimestamp(columnIndex));
				return calendar;
			}
		}
		return null;
	}

}
